package com.sojoys.artifact.manager;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.sojoys.artifact.constant.ArtifactErrorCode;
import com.sojoys.artifact.tools.ToolError;
import com.xiaoleilu.hutool.log.Log;
import com.xiaoleilu.hutool.log.LogFactory;

/**
 * @author : DengYing
 * @CreateDate : 2017年4月6日 下午6:32:44
 * @Description ：线程池管理器
 */
public class ThreadManager {
	
	private ThreadManager() {
	}

	private static ThreadManager ME = new ThreadManager();

	public static ThreadManager me() {
		return ME;
	}
	
	static Log log = LogFactory.get(ThreadManager.class);
	

	Map<String, ThreadPoolTaskExecutor> threadPoolTaskExecutor = new HashMap<>();

	public ThreadPoolTaskExecutor getThreadPoolTaskExecutor(String name){
		return threadPoolTaskExecutor.get(name);
	}
	
	public Map<String, ThreadPoolTaskExecutor> getThreadPoolTaskExecutor() {
		return threadPoolTaskExecutor;
	}

	public void setThreadPoolTaskExecutor(Map<String, ThreadPoolTaskExecutor> threadPoolTaskExecutor) {
		this.threadPoolTaskExecutor = threadPoolTaskExecutor;
	}
	
	/**
	 * 选定线程池执行
	 * @param poolName
	 * @param runnable
	 * @throws NotFondExecutorException
	 */
	public void execute(String poolName,Runnable runnable){
		ThreadPoolTaskExecutor executor = threadPoolTaskExecutor.get(poolName);
		ToolError.isAndTrue(ArtifactErrorCode.NOT_FOND_EXECUTOR, executor==null);
		executor.execute(runnable);
	}
	/**
	 * 停止所有线程
	 */
	public void stop(){
		Set<Entry<String, ThreadPoolTaskExecutor>> es = threadPoolTaskExecutor.entrySet();
		for (Entry<String, ThreadPoolTaskExecutor> e : es) {
			ThreadPoolTaskExecutor pool = e.getValue();
			pool.destroy();
		}
		log.info("-> threadPoolTaskExecutor destroy all");
	}
}
